package com.xf.zk.curator.example.znode;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

public class CreateNodeBackground {
	static String path = "/curator-create-backGround/c1";
	// 创建CuratorFramework 客户端实例，集群服务器地址为127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183，session timeout5000ms
	// 回调策略为ExponentialBackoffRetry，即为retries 3 times with increasing 1000 sleep time between retries
	static CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183")
			.sessionTimeoutMs(5000).retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
	// 2个信号量，BackGround 回调callBack成功再停止
	static CountDownLatch semaphore = new CountDownLatch(2);
	// 固定线程池，2个线程
	static ExecutorService es = Executors.newFixedThreadPool(2);

	public static void main(String[] args) throws Exception {
		// 开始连接
		client.start();
		System.out.println("Main thread: " + Thread.currentThread().getName());

		// 创建 EPHEMERAL类型节点，并创建父节点，使用一部线程background方式处理创建结果
		client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).inBackground(new BackgroundCallback() {
			public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
				// 打印事件信息
				System.out.println("event[code: " + event.getResultCode() + ", type: " + event.getType() + "]" + ", Thread of processResult: " + Thread.currentThread().getName());
				System.out.println();
				semaphore.countDown();
			}
		}, es).forPath(path, "init".getBytes());

		// 创建相同路径节点
		client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).inBackground(new BackgroundCallback() {
			public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
				// 打印事件信息
				System.out.println("event[code: " + event.getResultCode() + ", type: " + event.getType() + "]" + ", Thread of processResult: " + Thread.currentThread().getName());
				semaphore.countDown();
			}
		}).forPath(path, "init".getBytes());

		semaphore.await();
		// 关闭线程池
		es.shutdown();
		// 关闭连接
		client.close();
	}
}
